package com.rec.smile.rpc.api.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

public class SerializationUtil {

	private static Map<Class<?>, Schema<?>>  cacheSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();
	
	private static Objenesis objenesis = new ObjenesisStd(true);

	private SerializationUtil() {
		super();
	}
	
	private static <T> Schema<T> getSchema(Class<T> cls){
		Schema<T> schema = (Schema<T>) cacheSchema.get(cls);
		if(schema == null){
			schema = RuntimeSchema.createFrom(cls);
			if(schema != null){
				cacheSchema.put(cls, schema);
				
			}
		}
		return schema;
	}
	
	
	public static <T> byte[] serialize(T obj){
		Class<T> cls = (Class<T>) obj.getClass();
		LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
		try {
			return ProtobufIOUtil.toByteArray(obj, getSchema(cls), buffer);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}finally{
			buffer.clear();
		}
	}
	
	public static <T> T deserialize(byte[] bytes, Class<T> cls){
		T message = objenesis.newInstance(cls);
		ProtobufIOUtil.mergeFrom(bytes, message, getSchema(cls));
		return message;
	}
	
}
